import sys
import os
import urllib
import time

from tvkaista import get_data
from tvkaista import TVKaistaURLopener
from tvkaista import CACHEDIR

def _read_int(text):
    x = None
    while x is None:
        try:
            x = int(raw_input(text))
        except ValueError:
            print 'Invalid Number'
    return x

# Command line interface

def show_options(rss):
    """
    Print options found from rss['items'] in a numbered list
    starting from 1 and return selected *index* of selection (given number minus 1)
    """
    layout = u"%(i)3d. %(title)s"
    i = 0
    options = []
    options.append(layout % {'i': 0, 'title': u'Back'})
    for item in rss['items']:
        i += 1
        item['i'] = i
        options.append(layout % item)
    print rss['title'] + "\n" + "\n".join(options)
    num = _read_int("Select option number: ")
    return num

def show_program_options(rss, selected = []):
    layout = u"%(sel)s %(i)3d. %(hhmm)s %(title)s (%(dur)s min)"
    i = 0
    options = []
    options.append(u'  0. Back')
    for item in rss['items']:
        i += 1
        item['i'] = i
        # Print * prefix if item is already selected
        if selected.count(i) == 1:
            item['sel'] = '*'
        else:
            item['sel'] = ' '
        if 'pubDate' not in item: # not published yet
            continue
        item['hhmm'] = item['pubDate'].strftime('%d.%m. %H:%M')
        item['dur'] = u''
        for m in item['media']:
            if m['type'] == u'video/mp2t':
                item['dur'] = m['duration']/60
                break
        options.append(layout % item)
    print rss['title'] + "\n" + "\n".join(options)
    # TODO: create real parser function for this
    input = raw_input("Enter one or more numbers between 1-%d: " % len(rss['items']))
    # selected = []
    for x in input.split(" "):
        r = [int(y) for y in x.split('-')]
        if len(r) > 1:
            selected.extend(range(r[0], r[1] + 1))
        else:
            selected.append(r[0])
    # remove duplicates
    keys = {}
    for e in selected:
        keys[e] = 1
    selected = keys.keys()
    selected.sort()
    return selected 

def show_programs(rss):
    """
    Print all available programs in selected feed.
    """
    selected = show_program_options(rss)
    while selected.count(0) == 0:
        print selected
        #print rss['items'][num - 1]
        selected = show_program_options(rss, selected)
        # print rss['items'][selected[0]]
    print "Back" 
    return

def show_search():
    """
    Show search dialog.
    """
    prompt = 'Enter search terms (empty stops): '
    search = raw_input(prompt)
    while search:
        url = "http://alpha.tvkaista.fi/feed/search/title/%s/flv.mediarss" % search
        programs_rss = get_data(url)
        show_programs(programs_rss)
        search = raw_input(prompt)
    print "Back" 
    return


def show_channels(rss):
    """
    Print all available options in selected feed, 
    e.g. channels or seasonpasses.
    """
    #print "\n".join(rss['items'])
    #print rss['items'][0]
    num = show_options(rss)
    while num > 0:
        if num <= len(rss['items']):
            url = rss['items'][num - 1]['link']
            print num, url
            programs_rss = get_data(url)
            show_programs(programs_rss)
        #print programs_rss['items'][3]
        num = show_options(rss)
    print "Back" 
    return

def show_feed(rss):
    """Print all available options in root feed."""
    num = show_options(rss)
    while num > 0: # Loop until user enters 0
        if num <= len(rss['items']):
            title = rss['items'][num - 1]['title'].lower()
            if title.find('search') >= 0:
                # Search is special case
                print "Search"
                show_search()
            elif title.find('play') >= 0 or title.find('storage') >= 0:
                # print rss['items']
                url = rss['items'][num - 1]['link']
                programs_rss = get_data(url)
                show_programs(programs_rss)
            else:
                url = rss['items'][num - 1]['link']
                print num, url
                channel_rss = get_data(url)
                show_channels(channel_rss)
        num = show_options(rss)
    print "Back"
    return

if __name__ == '__main__':
    url = 'http://alpha.tvkaista.fi/feed/'
    pwfile = 'username.txt'
    if os.path.isfile(pwfile):
        user = eval(open(pwfile, 'rt').read())
        username = user['username']
        password = user['password']
    else:
        username = raw_input("TVKaista username: ")
        password = raw_input("TVKaista password: ")
        f = open(pwfile, 'wt')
        f.write(repr({'username': username, 'password': password}))
    urllib._urlopener = TVKaistaURLopener(username, password)
    #import tempfile
    #global CACHEDIR
    #CACHEDIR = tempfile.mkdtemp()
    print "Using CACHEDIR for RSS-feeds: %s" % (CACHEDIR)
    # Get channel list
    rss = get_data(url)
    show_feed(rss)
    sys.exit()
